<?php

namespace App\Jobs;

use App\Models\ImFriendsCircle;
use App\Models\ImFriendsCircleImgs;
use App\Models\ImQueueErrorLogs;
use App\Services\Aliyun\Video\VideoServices;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ImgTask implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $data = null;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data = null)
    {
        //
        $this->data = $data;
    }

    /**
     * @desc 队列自动审核朋友圈的图片
     * @return bool
     * @author zhouzhou
     * @time 2021/12/20 18:34
     */
    public function handle()
    {
        // redis的数据
        $data = $this->data;
        if (!empty($data))
        {
            try
            {
                $fcId = $data['fc_id'];

                $fileAIMediaAuditJob = new VideoServices();
                $ImFriendsCircleModel = new ImFriendsCircle();
                $imFriendsCircleImgs = new ImFriendsCircleImgs();

                $circleImgsList = $imFriendsCircleImgs->where(['fc_id'=>$fcId])
                    ->orderBy('id', 'desc')
                    ->get();

                $flag = 0;
                $remark = 'ok';
                foreach ($circleImgsList as $k =>&$v)
                {
                    $taskId = $v['file_id'];
                    $res = $fileAIMediaAuditJob->getAIMediaAuditJobInfo($taskId, $v['type'] - 1); //$taskId智能检测任务ID(可获取智能检查结果）
                    $result = $res['data'][0]['results'];

                    foreach ($result as $ke =>&$va)
                    {
                        if ($va['suggestion'] != 'pass')
                        {
                            $flag = 1;
                            $remark = ($va['label'] == 'porn') ? '涉黄' : '涉政';
                        }
                    }
                }

                $status = ($flag == 0) ? 1 : 2; // flag 等于0 ，都是正常的，1有一个涉黄涉恐
                $ImFriendsCircleModel->where(['id' => $fcId])->update(["status" => $status, "remark" => $remark]);
            } catch (\Exception $e)
            {
                $imQueueErrorLogs = new ImQueueErrorLogs();
                $imQueueErrorLogs->insertQueueError(json_encode(['data'=>$data]), 5, $e->getMessage());
            }
        }

        return true;
    }
}
